public class Solution {
    public void swap(int[] num, int i, int j) {
        int t = num[i];
        num[i] = num[j];
        num[j] = t;
    }
    
    public void reverse(int[] num, int start) {
        int n = num.length;
        for (int i = 0; i<(n-start)/2; i++) 
            swap(num, i+start, n-i-1);
    }
    
    public void nextPermutation(int[] num) {
        int n = num.length;
        int x1 = n - 2;
        while (x1 >= 0 && num[x1] >= num[x1+1]) --x1;
        if (x1 == -1) {
            reverse(num, 0);
            return ;
        }
        
        int x2 = n-1;
        while (num[x2] <= num[x1]) --x2;
        swap(num, x1, x2);
        reverse(num, x1+1);
    }
}
